package com.service.scheduler.job;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.StatefulJob;

import com.service.bean.company.Company;
import com.service.bean.device.Vehicle;
import com.service.bean.notice.NoticeMessage;
import com.service.cache.CacheManager;
import com.service.db.impl.DbNotice;
import com.service.other.Logger;
import com.service.webservice.out.NoticeMessageResult;
import com.service.webservice.out.WebServiceServerNoticeMessageImpl;
import com.service.webservice.out.WebServiceServerNoticeMessageImplService;

/**
 * 2015年9月17日上午9:15:54
 *
 * wt
 */
@SuppressWarnings("deprecation")
public class NoticeMessageJob implements StatefulJob{

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		try {
			JobKey jk = context.getJobDetail().getKey();
			String jobName = jk.getName();
			String jobGroup = jk.getGroup();
			Logger.println("启动任务 [" + jobGroup + "].[" + jobName + "]");
							
			//把管道里的数据全部存到数据库
			for(Company company : CacheManager.instance().noticeMessageQueue.keySet()){
				DbNotice dbNotice = new DbNotice(company);
				while ((CacheManager.instance().noticeMessageQueue.get(company).peek()) != null) {
					NoticeMessage noticeMessage = CacheManager.instance().noticeMessageQueue.get(company).poll();
					dbNotice.insert(noticeMessage);
				}
			}

			//从数据库取出需要报警的消息
			String moCompany = "";
			for(Vehicle vehicle :CacheManager.instance().vehicleMap.values()){
				SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
				if(vehicle.lastGps == null || !format.format(new Date()).equals(format.format(vehicle.lastGps.gpsTime))){
					//防止多平台重复发送，依据是只在当前平台车辆存在时才继续处理
					continue;
				}

				if(moCompany.indexOf(vehicle.company.code)<0){
					moCompany += vehicle.company.code + ",";
					DbNotice dbNotice = new DbNotice(vehicle.company);
					//每个公司一次最多获得100条数据
					List<NoticeMessage> list = dbNotice.queryNoticeMessageNow();
					
					//调用webservice
					for(NoticeMessage noticeMessage:list){
						WebServiceServerNoticeMessageImplService factory=new WebServiceServerNoticeMessageImplService();	
						WebServiceServerNoticeMessageImpl wsService= factory.getWebServiceServerNoticeMessageImplPort();
						NoticeMessageResult result = wsService.noticeMessage(noticeMessage.getMsgId(), noticeMessage.getCompanyCode());					
						Logger.err("NoticeMessage:"+result.getCode()+result.getInfo());
					}
				}
			}
			Logger.println("任务执行完毕，下次启动时间：" + context.getNextFireTime());
		} catch (Exception e) {
			Logger.err(e);
		}
		
		
	}
}
